<template>
  <div class="min-h-screen bg-gray-50 p-6">
    <div class="max-w-7xl mx-auto">
      <a-typography-title :level="1" class="text-center mb-8">
        文本分词与替换工具
      </a-typography-title>
      
      <!-- 主要工作区域 - 三栏布局 -->
      <a-row :gutter="24" class="mb-6">
        
        <!-- 左侧：输入区域 -->
        <a-col :span="8">
          <a-card title="输入文本" :bordered="false">
            <a-textarea
              v-model:value="inputText"
              @input="handleInputChange"
              placeholder="请输入需要分词的文本，例如：我要吃苹果"
              :rows="8"
              :loading="isLoading"
            />
            <div class="mt-4">
              <a-button 
                @click="clearAll"
                type="default"
                block
                :icon="h(ClearOutlined)"
              >
                清空
              </a-button>
            </div>
          </a-card>
        </a-col>

        <!-- 中间：分词结果区域 -->
        <a-col :span="8">
          <a-card title="分词结果" :bordered="false">
            <div v-if="segmentedWords.length === 0" class="text-center py-8">
              <a-empty description="请先输入文本进行分词" />
            </div>
            <div v-else class="space-y-4">
              <div class="flex flex-wrap gap-2">
                <a-tag
                  v-for="(word, index) in segmentedWords"
                  :key="index"
                  @click="selectWord(word)"
                  :color="selectedWord === word ? 'blue' : 'default'"
                  class="cursor-pointer text-sm font-medium px-3 py-1"
                  :class="selectedWord === word ? 'transform scale-105' : ''"
                >
                  {{ word }}
                </a-tag>
              </div>
              
              <!-- 词汇替换控制区域 -->
              <div v-if="selectedWord" class="border-t pt-4">
                <a-typography-title :level="4" class="mb-3">
                  替换 "{{ selectedWord }}"
                </a-typography-title>
                
                <!-- 可搜索的选择器 -->
                <div class="mb-3">
                  <a-select
                    v-model:value="selectedReplacement"
                    show-search
                    placeholder="搜索并选择替换词汇..."
                    :filter-option="false"
                    :loading="searchLoading"
                    @search="handleSearch"
                    @select="handleSelectReplacement"
                    class="w-full"
                    :options="selectOptions"
                  />
                </div>

                <!-- 添加自定义替换词 -->
                <div class="mb-3">
                  <a-input-group compact>
                    <a-input
                      v-model:value="newReplacement"
                      @keyup.enter="addCustomReplacement"
                      placeholder="添加自定义替换词..."
                      style="width: calc(100% - 80px)"
                    />
                    <a-button
                      @click="addCustomReplacement"
                      :disabled="!newReplacement.trim()"
                      type="primary"
                      :icon="h(PlusOutlined)"
                    >
                      添加
                    </a-button>
                  </a-input-group>
                </div>

                <!-- 当前替换词列表 -->
                <div v-if="getWordReplacements(selectedWord).length > 0">
                  <a-typography-text type="secondary" class="text-sm mb-2 block">
                    当前替换词
                  </a-typography-text>
                  <div class="flex flex-wrap gap-1">
                    <a-tag
                      v-for="replacement in getWordReplacements(selectedWord)"
                      :key="replacement"
                      closable
                      @close="removeWordRelation(selectedWord, replacement)"
                      color="processing"
                      class="text-xs"
                    >
                      {{ replacement }}
                    </a-tag>
                  </div>
                </div>
              </div>
            </div>
          </a-card>
        </a-col>

        <!-- 右侧：替换后文本区域 -->
        <a-col :span="8">
          <a-card title="替换结果" :bordered="false">
            <div v-if="!replacedText" class="text-center py-8">
              <a-empty description="选择词汇进行替换后，结果将显示在这里" />
            </div>
            <div v-else class="space-y-4">
              <div class="p-4 bg-gray-50 rounded-lg border min-h-[200px]">
                <div class="text-gray-800 leading-relaxed" v-html="highlightedReplacedText"></div>
              </div>
              <div class="flex flex-col gap-2">
                <a-button
                  @click="copyToClipboard"
                  type="default"
                  block
                  :icon="h(CopyOutlined)"
                >
                  复制文本
                </a-button>
                <a-button
                  @click="saveRecord"
                  type="primary"
                  block
                  :icon="h(SaveOutlined)"
                >
                  保存记录
                </a-button>
              </div>
            </div>
          </a-card>
        </a-col>
      </a-row>

      <!-- 历史记录区域 -->
      <div class="bg-white rounded-lg shadow-md p-6">
        <h2 class="text-xl font-semibold text-gray-800 mb-4">历史记录</h2>
        <div v-if="textRecords.length === 0" class="text-gray-500 text-center py-8">
          暂无历史记录
        </div>
        <div v-else class="space-y-4">
          <div
            v-for="record in textRecords"
            :key="record.id"
            class="p-4 border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors"
          >
            <div class="flex justify-between items-start mb-2">
              <span class="text-sm text-gray-500">{{ formatDate(record.createdAt) }}</span>
            </div>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <h4 class="font-medium text-gray-700 mb-1">原文本</h4>
                <p class="text-sm text-gray-600 bg-gray-50 p-2 rounded">{{ record.originalText }}</p>
              </div>
              <div>
                <h4 class="font-medium text-gray-700 mb-1">替换后</h4>
                <p class="text-sm text-gray-600 bg-gray-50 p-2 rounded">{{ record.replacedText }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
     </div>
   </div>
 </template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, h } from 'vue'
import { ClearOutlined, PlusOutlined, CopyOutlined, SaveOutlined } from '@ant-design/icons-vue'

// 响应式数据
const inputText = ref('')
const segmentedWords = ref<string[]>([])
const selectedWord = ref('')
const selectedReplacement = ref<string>('')
const searchLoading = ref(false)
const replaceableWords = ref<{word: string, frequency: number}[]>([])
const newReplacement = ref('')
const replacements = ref<Record<string, string[]>>({})
const textRecords = ref<any[]>([])
const isLoading = ref(false)
let debounceTimer: number | null = null

// API 基础URL
const API_BASE = 'http://localhost:3000'

// 计算选择器选项
const selectOptions = computed(() => {
  return replaceableWords.value.map(item => ({
    value: item.word,
    label: `${item.word} (频率: ${item.frequency})`,
  }))
})

// 计算替换后的文本
const replacedText = computed(() => {
  if (!inputText.value || Object.keys(replacements.value).length === 0) {
    return ''
  }
  
  let result = inputText.value
  for (const [original, replaceList] of Object.entries(replacements.value)) {
    if (replaceList.length > 0) {
      // 使用第一个替换词
      const replacement = replaceList[0]
      const escapedOriginal = original.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
      result = result.replace(new RegExp(escapedOriginal, 'g'), replacement)
    }
  }
  return result
})

// 计算高亮显示的替换后文本
const highlightedReplacedText = computed(() => {
  if (!replacedText.value) return ''
  
  let result = replacedText.value
  const replacedWords = new Set<string>()
  
  // 收集所有被替换的词
  for (const [original, replaceList] of Object.entries(replacements.value)) {
    if (replaceList.length > 0) {
      replacedWords.add(replaceList[0])
    }
  }
  
  // 高亮显示被替换的词
  replacedWords.forEach(word => {
    if (word) {
      const escapedWord = word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
      const regex = new RegExp(`(${escapedWord})`, 'g')
      result = result.replace(regex, '<span class="bg-yellow-200 px-1 rounded font-medium">$1</span>')
    }
  })
  
  return result
})

// 防抖处理输入变化
const handleInputChange = () => {
  if (debounceTimer) {
    clearTimeout(debounceTimer)
  }
  
  debounceTimer = setTimeout(() => {
    // 清空之前的分词结果
    segmentedWords.value = []
    selectedWord.value = ''
    replacements.value = {}
    
    // 如果有输入内容，自动进行分词
    if (inputText.value.trim()) {
      segmentText()
    }
  }, 500) // 500ms 防抖
}

// 分词功能
const segmentText = async () => {
  if (!inputText.value.trim()) return
  
  isLoading.value = true
  try {
    const response = await fetch(`${API_BASE}/word/segment`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ text: inputText.value }),
    })
    
    if (response.ok) {
      const data = await response.json()
      segmentedWords.value = data.data?.segments || []
    } else {
      console.error('分词失败:', response.statusText)
      // 如果API失败，使用简单的分词作为后备
      segmentedWords.value = inputText.value.split(/[\s，。！？；：、""''（）【】《》〈〉「」『』〔〕［］｛｝]+/).filter(word => word.trim())
    }
  } catch (error) {
    console.error('分词请求失败:', error)
    // 使用简单的分词作为后备
    segmentedWords.value = inputText.value.split(/[\s，。！？；：、""''（）【】《》〈〉「」『』〔〕［］｛｝]+/).filter(word => word.trim())
  } finally {
    isLoading.value = false
  }
}

// 选择词汇
const selectWord = (word: string) => {
  selectedWord.value = word
  selectedReplacement.value = ''
  replaceableWords.value = []
  // 加载该词的替换词
  loadReplaceableWords(word)
}

// 处理搜索
const handleSearch = async (searchValue: string) => {
  if (!selectedWord.value) return
  
  searchLoading.value = true
  try {
    if (searchValue.trim()) {
      const response = await fetch(`${API_BASE}/word/replaceable/${encodeURIComponent(selectedWord.value)}?search=${encodeURIComponent(searchValue)}`)
      
      if (response.ok) {
        const data = await response.json()
        replaceableWords.value = data.data || []
      }
    } else {
      await loadReplaceableWords(selectedWord.value)
    }
  } catch (error) {
    console.error('搜索替换词失败:', error)
  } finally {
    searchLoading.value = false
  }
}

// 处理选择替换词
const handleSelectReplacement = (value: string) => {
  if (selectedWord.value && value) {
    replaceWord(selectedWord.value, value)
    selectedReplacement.value = ''
  }
}

// 加载可替换词汇
const loadReplaceableWords = async (word: string) => {
  try {
    const response = await fetch(`${API_BASE}/word/replaceable/${encodeURIComponent(word)}`)
    
    if (response.ok) {
      const data = await response.json()
      replaceableWords.value = data.data || []
    }
  } catch (error) {
    console.error('加载替换词失败:', error)
  }
}

// 获取词汇的替换词列表
const getWordReplacements = (word: string): string[] => {
  return replacements.value[word] || []
}

// 直接替换词汇
const replaceWord = (original: string, replacement: string) => {
  if (!replacements.value[original]) {
    replacements.value[original] = []
  }
  
  // 清空之前的替换，只保留当前选择的
  replacements.value[original] = [replacement]
  
  // 保存到后端
  addWordRelation(original, replacement)
}

// 添加词汇关系
const addWordRelation = async (sourceWord: string, targetWord: string) => {
  try {
    await fetch(`${API_BASE}/word/relation`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        sourceWord,
        targetWord,
      }),
    })
  } catch (error) {
    console.error('保存词汇关系失败:', error)
  }
}

// 添加自定义替换词
const addCustomReplacement = () => {
  if (newReplacement.value.trim() && selectedWord.value) {
    replaceWord(selectedWord.value, newReplacement.value.trim())
    newReplacement.value = ''
    // 重新加载可替换词汇
    loadReplaceableWords(selectedWord.value)
  }
}

// 移除词汇关系
const removeWordRelation = async (sourceWord: string, targetWord: string) => {
  if (replacements.value[sourceWord]) {
    const index = replacements.value[sourceWord].indexOf(targetWord)
    if (index > -1) {
      replacements.value[sourceWord].splice(index, 1)
      
      // 从后端删除
      try {
        await fetch(`${API_BASE}/word/relation`, {
          method: 'DELETE',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            sourceWord,
            targetWord,
          }),
        })
      } catch (error) {
        console.error('删除词汇关系失败:', error)
      }
    }
  }
}

// 复制到剪贴板
const copyToClipboard = async () => {
  if (replacedText.value) {
    try {
      await navigator.clipboard.writeText(replacedText.value)
      // 可以添加 Ant Design 的 message 提示
    } catch (error) {
      console.error('复制失败:', error)
    }
  }
}

// 保存记录
const saveRecord = async () => {
  if (!segmentedWords.value.length) return
  
  try {
    await fetch(`${API_BASE}/word/record`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        originalText: inputText.value,
        segmentedWords: segmentedWords.value,
        replacedText: replacedText.value,
        replacements: replacements.value
      })
    })
    
    // 重新加载历史记录
    loadHistoryRecords()
  } catch (error) {
    console.error('保存记录失败:', error)
  }
}

// 加载历史记录
const loadHistoryRecords = async () => {
  try {
    const response = await fetch(`${API_BASE}/word/records?pageNum=1&limitNum=10`)
    
    if (response.ok) {
      const data = await response.json()
      textRecords.value = data.data?.records || []
    }
  } catch (error) {
    console.error('加载历史记录失败:', error)
  }
}

// 清空所有内容
const clearAll = () => {
  inputText.value = ''
  segmentedWords.value = []
  selectedWord.value = ''
  selectedReplacement.value = ''
  replaceableWords.value = []
  replacements.value = {}
}

// 格式化日期
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 组件挂载时加载历史记录
onMounted(() => {
  loadHistoryRecords()
})
</script>

<style scoped>
/* 自定义样式 */
</style>